package com.modudf.common;

import java.awt.Component;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

public class SwingAnimation
  implements ActionListener
{
  private Timer animationTimer;
  private long startTime;
  private int animationTime;
  private Component component;
  private Point pTarget;
  private int stepX;
  private int stepY;
  private int animationDelay = 20;
  private Rectangle desktopBounds;
  
  public SwingAnimation(Component component, int animationTime)
  {
    this.component = component;
    this.animationTime = animationTime;
    GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
    
    this.desktopBounds = env.getMaximumWindowBounds();
  }
  
  public void flyToRB()
  {
    this.pTarget = new Point(this.desktopBounds.width - this.component.getWidth(), this.desktopBounds.height - this.component.getHeight());
    
    fly();
  }
  
  public void flyToLB()
  {
    this.pTarget = new Point(0, this.desktopBounds.height - this.component.getHeight());
    fly();
  }
  
  private void fly()
  {
    int offsetX = this.pTarget.x - this.component.getX();
    int offsetY = this.pTarget.y - this.component.getY();
    
    int step = this.animationTime / this.animationDelay;
    this.stepX = (offsetX / step);
    this.stepY = (offsetY / step);
    
    this.startTime = System.currentTimeMillis();
    this.animationTimer = new Timer(this.animationDelay, this);
    this.animationTimer.start();
  }
  
  public void actionPerformed(ActionEvent e)
  {
    long elapsed = System.currentTimeMillis() - this.startTime;
    if (elapsed > this.animationTime)
    {
      this.component.setLocation(this.pTarget);
      this.animationTimer.stop();
      this.animationTimer = null;
    }
    else
    {
      Point p = this.component.getLocation();
      this.component.setLocation(p.x + this.stepX, p.y + this.stepY);
    }
  }
}
